package my.diplom.web.controllers;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.validation.BindException;
import my.diplom.entity.Category;
import my.diplom.entity.HostCard;
import my.diplom.entity.Host;
import my.diplom.dao.service.HostCardService;
import my.diplom.dao.service.HostService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.HashMap;

/**
 * Created by IntelliJ IDEA.
 * User: gb
 * Date: 22.12.2009
 * Time: 23:55:17
 * To change this template use File | Settings | File Templates.
 */
public class HostCardController extends SimpleFormController {

    private HostService hostService;
    private HostCardService hostCardService;

    public void setHostService(HostService hostService) {
        this.hostService = hostService;
    }

    public void setHostCardService(HostCardService hostCardService) {
        this.hostCardService = hostCardService;
    }

    public HostCardController() {
        setCommandClass(HostCard.class);
        setCommandName("newHostCard");
        setSessionForm(false);
        setBindOnNewForm(false);
    }

    @Override
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        if (request.getParameter("id") != null) {
            Long id = Long.parseLong(request.getParameter("id"));
            Host host = hostService.getById(id);
            if (host.getHostCard() != null) return host.getHostCard();
            HostCard hostCard = new HostCard();
            host.setHostCard(hostCard);
            hostService.update(host);
            return host.getHostCard();
        }
        return null;
    }


    @Override
    protected Map referenceData(HttpServletRequest request) throws Exception {
        HashMap<String, Object> model = new HashMap<String, Object>();
        if (request.getParameter("id") != null) {
            Long id = Long.parseLong(request.getParameter("id"));
            Host host = hostService.getById(id);
            HostCard hostCard = hostCardService.getById(id);
            model.put("host", host);
            model.put("hostCard", hostCard);
        }
        return model;
    }

    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, BindException e) throws Exception {
        HostCard hostCard = (HostCard) o;
        hostCardService.create(hostCard);
        return new ModelAndView(new RedirectView("hostCard.htm?id=" + hostCard.getHostCartId()));
    }


}
